package com.hzit.hzb.core.controller.api;


import com.alibaba.fastjson.JSON;
import com.hzit.common.result.R;
import com.hzit.hzb.base.util.JwtUtils;
import com.hzit.hzb.core.hfb.RequestHelper;
import com.hzit.hzb.core.pojo.entity.LendReturn;
import com.hzit.hzb.core.service.LendReturnService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 还款记录表 前端控制器
 * </p>
 *
 * @author hbxfwf
 * @since 2024-08-27
 */
@RestController
@RequestMapping("/api/core/lendReturn")
@Slf4j
public class LendReturnController {
	@Autowired
	private LendReturnService lendReturnService;

	/**
	 * 根据标的id查询还款记录列表
	 * @param id
	 * @return
	 */
	@GetMapping("/fetchLendReturnList/{id}")
	public R fetchLendReturnList(@PathVariable("id") Long id){
		List<LendReturn> lendReturnList = lendReturnService.fetchLendReturnList(id);
		return R.ok().data("list",lendReturnList);
	}

	/**
	 * 还款
	 * @param lendReturnId
	 * @return
	 */
	@PostMapping("/auth/commitReturn/{lendReturnId}")
	public R commitReturn(@PathVariable("lendReturnId") Long lendReturnId,@RequestHeader("token") String token){
		String formStr = lendReturnService.commitReturn(lendReturnId, JwtUtils.getUserId(token));
		return R.ok().data("formStr",formStr);
	}

	/**
	 * 还款的异步回调
	 * @param request
	 * @return
	 */
	@PostMapping("/notifyUrl")
	public String notifyUrl(HttpServletRequest request){
		// 1.1 转换请求的数据为Map<String,String>格式
		Map<String, Object> paramMap = RequestHelper.switchMap(request.getParameterMap());
		// 1.2 进行验签处理
		if(RequestHelper.isSignEquals(paramMap)){
			if("0001".equals(paramMap.get("resultCode").toString())){
				return lendReturnService.notifyUrl(paramMap);
			}else {
				log.info("还款异步回调失败：" + JSON.toJSONString(paramMap));
				return "fail";
			}
		} else {
			log.info("还款异步回调签名错误：" + JSON.toJSONString(paramMap));
			return "fail";
		}
	}
}

